package com.ronri.ams.task;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.ronri.CustomDialog;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.ams.bean.sampleList;
import com.ronri.ams.bean.sample_info;
import com.ronri.ams.bean.tb_sampleinfo;
import com.ronri.ams.sample.activity_control_photograph;
import com.ronri.common.BitmapManager;
import com.ronri.common.FileManager;
import com.ronri.common.StringManager;
import com.ronri.common.UrlEncode;
import com.ronri.common.WaitDialog;
import com.ronri.db.RemoteDataService;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * Created by Administrator on 2017/5/7.
 */

public class activity_sample_info_already_upload extends com.ronri.ams.sample.abstract_activity {

    private ListView mListView = null;
    // 列表数据
    private List<Map<String, Object>> mItems = new ArrayList<Map<String, Object>>();
    private List<tb_sampleinfo> mlist = new ArrayList<>();
    private Context mContext = null;
    private sample_info mSampleInfo = null;
    private int mPid = -1;
    private int mTid = -1;
    private String mFilePath = "";
    private String mFileName = "";
    private String mSampleId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.sample_info_already_upload_list);
        Log.i("aaa", "activity_sample_info_already_upload");
        setTitle("已上传样品", "");
        init();
        mContext = this;
        Bundle bundle = getIntent().getExtras();
        TextView textView = (TextView) findViewById(R.id.task_title);

        if (bundle != null) {
            String szJson = bundle.getString("data");
            mlist = JSON.parseArray(szJson, tb_sampleinfo.class);

            mPid = bundle.getInt("pid");
            mTid = bundle.getInt("tid");

            //            int i = 0;
            //            for (tb_sampleinfo item : mlist) {
            //                if (item.getStatus().equals("0") || item.getStatus() == null) {
            //                    Map<String, Object> ii = new HashMap<String, Object>();
            //
            //                    ii.put("dept", "" + item.getEntname());
            //                    ii.put("user", "" + item.getHumen());
            //                    ii.put("date", "" + item.getDtime());
            //                    ii.put("samplename", "" + item.getSamplename());
            //                    ii.put("sampleimg", R.id.imgSamplePhoto);
            //                    ii.put("positon", i);
            //                    mItems.add(ii);
            //                }
            //                i++;
            //            }

            String szTitle = bundle.getString("title");
            textView.setText(szTitle);
        }

        // 加载列表视图控件
        mListView = (ListView) findViewById(R.id.list_sample_info_already_upload);

        //        // Item适配器
        //        SimpleAdapterDetailWithEvent adapter = new SimpleAdapterDetailWithEvent(
        //                this,
        //                R.layout.v_sample_already_upload,
        //                mItems,
        //                new int[]{R.id.bt_print, R.id.bt_sample_upload},
        //                new OnControlClickEvent() {
        //                    @Override
        //                    public void OnClick(View view, final int Target) {
        //                        if (view instanceof Button) {
        //                            if (view.getId() == R.id.bt_sample_upload) {
        //
        //                                tb_sampleinfo info = mlist.get(Target);
        //
        //                                if (info == null)
        //                                    return;
        //
        //                                if (StringManager.isEmpty(info.getJson())) {
        //                                    return;
        //                                }
        //
        //                                List<String> lFiles = new ArrayList<>();
        //
        //                                // 转换
        //                                mSampleInfo = JSON.parseObject(info.getJson(), sample_info.class);
        //
        //                                // 判断用户是否选择了2个
        //                                if (StringManager.InitString(mSampleInfo.getSample_user()).indexOf(",") == -1) {
        //                                    CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
        //                                    builder.setMessage("抽样人员至少需要2人，请继续编辑...");
        //                                    builder.setTitle("信息提示");
        //                                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
        //                                        public void onClick(DialogInterface dialog, int which) {
        //                                            dialog.dismiss();
        //                                        }
        //                                    });
        //                                    builder.create().show();
        //
        //                                    return;
        //                                }
        //
        //                                // 组合上传照片，并合并到目标里去
        //                                for (sample_info.SampleAttachBean item : mSampleInfo.getSample_attach()) {
        //                                    lFiles.add(item.getAttach_name());
        //                                }
        //
        //                                // 组合上传照片，并合并到目标里去
        //                                for (sample_info.SampleSignBean item : mSampleInfo.getSample_sign()) {
        //                                    lFiles.add(item.getAttach_name());
        //                                }
        //
        //                                if(mSampleInfo.getSample_breed() !=null)
        //                                for (sample_info.SampleBreedBean item : mSampleInfo.getSample_breed()) {
        //                                    for (sample_info.SampleBreedBean.BreedAttachBean ii : item.getBreed_attach()) {
        //                                        lFiles.add(ii.getAttach_name());
        //                                    }
        //                                }
        //
        //                                RemoteDataService rdb = new RemoteDataService();
        //                                rdb.postMFileToRemote("http://192.168.0.77:8080/ams/api/uploadPhoto.json", lFiles, null, new RemoteDataService.OnRemoteDataEvent() {
        //                                    @Override
        //                                    public void OnResultEvent(String szString) {
        //
        //                                        filepostbean bean = JSON.parseObject(szString, filepostbean.class);
        //
        //                                        if (bean.isSuccess()) {
        //                                            for (filepostbean.DataBean item : bean.getData()) {
        //
        //                                                // 组合上传照片，并合并到目标里去
        //                                                for (sample_info.SampleAttachBean photo : mSampleInfo.getSample_attach()) {
        //                                                    if (photo.getAttach_name().indexOf(item.getName()) != -1) {
        //                                                        photo.setAttach_url(item.getUrl());
        //                                                    }
        //                                                }
        //
        //                                                // 组合上传照片，并合并到目标里去
        //                                                for (sample_info.SampleSignBean photo : mSampleInfo.getSample_sign()) {
        //                                                    if (photo.getAttach_name().indexOf(item.getName()) != -1) {
        //                                                        photo.setAttach_url(item.getUrl());
        //                                                    }
        //                                                }
        //
        //                                                // 组合上传照片，并合并到目标里去
        //                                                for (sample_info.SampleBreedBean photo : mSampleInfo.getSample_breed()) {
        //                                                    for (sample_info.SampleBreedBean.BreedAttachBean ii : photo.getBreed_attach()) {
        //                                                        if (ii.getAttach_name() != null)
        //                                                            if (ii.getAttach_name().indexOf(item.getName()) != -1) {
        //                                                                ii.setAttach_url(item.getUrl());
        //                                                            }
        //                                                    }
        //                                                }
        //                                            }
        //
        //                                            String szJson = JSON.toJSONString(mSampleInfo);
        //
        //                                            RemoteDataService rrr = new RemoteDataService();
        //
        //                                            rrr.getRemoteData("http://192.168.0.77:8080/ams/api/uploadSample.json", szJson, "POST", new RemoteDataService.OnRemoteDataEvent() {
        //                                                @Override
        //                                                public void OnResultEvent(String szString) {
        //                                                    int nid = mlist.get(Target).getId();
        //                                                    mlist.get(Target).setStatus("1");
        //                                                    mlist.get(Target).update(nid);
        //
        //
        //                                                }
        //
        //                                                @Override
        //                                                public void OnRuningState(int nStatus) {
        //                                                    if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
        //                                                        WaitDialog.ShowDialog(mContext, "正在上传数据，请稍后...");
        //                                                    } else {
        //                                                        WaitDialog.HideDialog();
        //                                                    }
        //                                                }
        //
        //                                                @Override
        //                                                public String OnGetCustomParam() {
        //                                                    return null;
        //                                                }
        //                                            });
        //                                        }
        //                                    }
        //
        //                                    @Override
        //                                    public void OnRuningState(int nStatus) {
        //                                        if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
        //                                            WaitDialog.ShowDialog(mContext, "正在上传记录附件，请稍后...");
        //                                        } else {
        //                                            WaitDialog.HideDialog();
        //                                        }
        //                                    }
        //
        //                                    @Override
        //                                    public String OnGetCustomParam() {
        //                                        return null;
        //                                    }
        //                                });
        //                            }
        //                        }
        //                    }
        //                });
        //
        //        // ListView绑定适配器
        //        listView.setAdapter(adapter);
        getRemoteData();
    }

    private void getRemoteData() {
        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                InitApplication.SystemConfig.getModule().getSampledetaillist().getAddress());

        Map<String, Object> mParam = new HashMap<String, Object>();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            mParam.put("page", 1);
            mParam.put("pageSize", 500);
            mParam.put("project_id", mPid);
            mParam.put("task_id", mTid);

        } catch (Exception ex) {

        }

        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getSampleslist().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {
                    // 返回结果
                    @Override
                    public void OnResultEvent(String szString) {
                        if (szString.isEmpty()) {
                            ShowNoData(true);
                            return;
                        }

                        Log.i("test","szString-->"+szString);
                        try {
                            sampleList mSmpleListBean = JSON.parseObject(szString, sampleList.class);

                            if (mSmpleListBean.isSuccess()) {
                                // mAlready.setText(mSmpleListBean.getData().getTotal());

                                if (mListView != null) {
                                    if (mSmpleListBean.getData().getRows().size() <= 0)
                                        ShowNoData(true);
                                    else {
                                        ShowNoData(false);

                                        // 获取List视图
                                        mListView = (ListView) findViewById(R.id.list_sample_info_already_upload);

                                        int i = 0;
                                        for (sampleList.DataBean.RowsBean item : mSmpleListBean.getData().getRows()) {
                                            Map<String, Object> ii = new HashMap<String, Object>();

                                            ii.put("id", item.getSample_id());
                                            ii.put("dept", "" + item.getInspectd_unit_name());
                                            ii.put("user", "" + item.getSample_user_name());
                                            ii.put("date", "" + item.getSample_date().substring(0, 10));
                                            ii.put("samplename", "" + item.getBreed_name());
                                            ii.put("positon", i);
//                                            Log.i("test","item-->"+item.toString());
                                            mItems.add(ii);
                                            i++;
                                        }

                                        SimpleAdapterDetailWithEvent adapter = new SimpleAdapterDetailWithEvent(
                                                mContext,
                                                R.layout.v_sample_already_upload,
                                                mItems,
                                                new int[]{R.id.bt_print, R.id.bt_sample_upload},
                                                new OnControlClickEvent() {

                                                    @Override
                                                    public void OnClick(View view, int Target) {
                                                        int nBtn = ((Button) view).getId();//.getText().toString();

                                                        if (nBtn == R.id.bt_print) {
                                                            final EditText et = new EditText(mContext);
                                                            final String szId = mItems.get(Target).get("id").toString();

                                                            et.setText("3");

                                                            final CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                                                            builder.setContentView(et);
                                                            builder.setTitle("打印份数");
                                                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    String inputName = et.getText().toString();
                                                                    dialog.dismiss();
                                                                    PrintSheet(Integer.parseInt(szId), Integer.parseInt(inputName));
                                                                }
                                                            });

                                                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int i) {
                                                                    dialog.dismiss();
                                                                }
                                                            });
                                                            builder.create().show();
                                                        }

                                                        if (nBtn == R.id.bt_sample_upload) {
                                                            mSampleId = mItems.get(Target).get("id").toString();
                                                            StartCamera();
                                                        }
                                                    }
                                                });

                                        mListView.setAdapter(adapter);
                                    }
                                }
                            }
                        } catch (Exception ex) {

                        }
                    }

                    // 状态控制，是否显示加载过程
                    @Override
                    public void OnRuningState(int nStatus) {
                        if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                            WaitDialog.ShowDialog(mContext, "请稍后...");
                        } else {
                            WaitDialog.HideDialog();
                        }
                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                }
        );
    }

    /***
     * 启动摄像头
     */
    public void StartCamera() {
        // 创建摄像头控制句柄
        Intent intent = new Intent(this, activity_control_photograph.class);

        // 创建目录，避免出现错误
        FileManager.DirExists(InitApplication.PhotoSavePath + "original/");

        // 生成文件名称
        mFileName = String.valueOf(System.currentTimeMillis()) + ".jpg";

        // 创建文件访问控制
        File file = new File(InitApplication.PhotoSavePath + "original/", mFileName);

        // 解析文件名称
        Uri imageUri = Uri.fromFile(file);

        // 获取文件名称
        mFilePath = imageUri.getPath();

        Bundle bundle = new Bundle();
        bundle.putString("photoFilePath", mFilePath);
        intent.putExtras(bundle);

        startActivityForResult(intent, InitApplication.Activity_RESULT_GET_PHOTO);
    }

    /****
     * 打印单
     *
     * @param sampleid
     * @param copies
     */
    public void PrintSheet(int sampleid, int copies) {
        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                InitApplication.SystemConfig.getModule().getPrintSheet().getAddress());

        Map<String, Object> mParam = new HashMap<String, Object>();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            mParam.put("user_id", InitApplication.LoginInfo.getData().getUser_id());
            mParam.put("sample_id", sampleid);
            mParam.put("copies", copies);

        } catch (Exception ex) {

        }

        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getSampleslist().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {
                    @Override
                    public void OnResultEvent(String szString) {
                        if (StringManager.InitString(szString).isEmpty())
                            return;

                        JSONObject jobject = JSONObject.parseObject(szString);
                        if (jobject.containsKey("message")) {
                            CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                            builder.setMessage(jobject.get("message").toString());
                            builder.setTitle("信息提示");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder.create().show();
                        }
                    }

                    @Override
                    public void OnRuningState(int nStatus) {

                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                }
        );
    }

    /***
     * 上传图片
     *
     * @param szFiles
     * @param sampleid
     */
    public void UpLoadSheet(String szFiles, int sampleid) {
        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                InitApplication.SystemConfig.getModule().getUpLoadSheet().getAddress());

        Map<String, Object> mParam = new HashMap<String, Object>();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            mParam.put("create_user", InitApplication.LoginInfo.getData().getUser_id());
            mParam.put("attach_name", FileManager.getTempFileName("png"));
            mParam.put("sample_id", sampleid);
            mParam.put("location", "");
            mParam.put("latitude", "");
        } catch (Exception ex) {

        }

        List<String> lFiles = new ArrayList<>();

        lFiles.add(szFiles);

        RemoteDataService rdb = new RemoteDataService();
        rdb.postMFileToRemote(szRemoteAddress, lFiles, mParam,
                new RemoteDataService.OnRemoteDataEvent() {
                    @Override
                    public void OnResultEvent(String szString) {
                        if (StringManager.InitString(szString).isEmpty())
                            return;

                        JSONObject jobject = JSONObject.parseObject(szString);
                        if (jobject.containsKey("success")) {
                            if ((boolean) jobject.get("success")) {
                                CustomDialog.Builder builder = new CustomDialog.Builder(mContext);

                                builder.setMessage(jobject.get("message").toString());
                                builder.setTitle("信息提示");
                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                                builder.create().show();
                            }
                        }
                    }

                    @Override
                    public void OnRuningState(int nStatus) {

                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                }
        );
    }

    /***
     * 创建演示数据
     */
    private void CreateDemo() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.home);

        Map<String, Object> obj = new HashMap<String, Object>();

        obj.put("dept", "盐城市盐都区王宏林家庭农场");
        obj.put("user", "吴冬梅,李鑫");
        obj.put("date", "2017-01-08");
        obj.put("samplename", "青椒");
        obj.put("sampleimg", bitmap);

        mItems.add(obj);

        obj = new HashMap<String, Object>();

        obj.put("dept", "盐城市盐都区千秋果蔬专业合作社");
        obj.put("user", "吴冬梅,李鑫");
        obj.put("date", "2017-01-08");
        obj.put("samplename", "大白菜、蔬菜");
        obj.put("sampleimg", bitmap);

        mItems.add(obj);
    }

    /***
     * 显示未找到数据
     *
     * @param bShow
     */
    private void ShowNoData(boolean bShow) {
        RelativeLayout rr = (RelativeLayout) findViewById(R.id.vNoData);
        if (rr != null) {
            if (bShow == true) {
                rr.setVisibility(View.VISIBLE);
            } else {
                rr.setVisibility(View.GONE);
            }
        }
    }

    /***
     * 处理照片返回
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == InitApplication.Activity_RESULT_GET_PHOTO) {
            if (resultCode == Activity.RESULT_OK) {

                if (mSampleId.isEmpty())
                    return;

                // 获取存储路径
                Bitmap bitmap = BitmapManager.getimage(mFilePath, 50);

                // 保存照片信息，进行压缩
                FileManager.saveCompressBitmap(
                        InitApplication.PhotoSavePath + "after/", mFileName,
                        bitmap,
                        100);

                if (!bitmap.isRecycled()) {
                    /// 释放内存
                    bitmap.recycle();
                    System.gc();
                }

                String szfile = InitApplication.PhotoSavePath + "after/" + mFileName;
                UpLoadSheet(szfile, Integer.parseInt(mSampleId));
            }
        }

    }
}
